const fs = require('fs');
const os = require('os')
const UUID = require('uuid')
const jwt = require('jsonwebtoken')
const log4js = require('./log4j')
const Email = require('./email')

exports.newFile = function(file, pathName) {
  // 检测是否有该路径文件夹
  if (!fs.existsSync('public' + pathName)) {
    log4js.debug('未找到该文件夹')
    return {
      success: false,
      message: '上传失败',
      files: [{ id: null, url: null, name: null }]
    }
  }
  if (file instanceof Array) {
    const arr = []
    file.forEach((item) => {
      //创建读取流
      const reader = fs.createReadStream(item.filepath)
      //创建写入流
      const stream = fs.createWriteStream(
        `public${pathName}/${
          moment().format('YYYY-MM-DD-HH-mm-ss-') +
          UUID.v4() +
          '.' +
          item.originalFilename.split('.').pop()
        }`
      )
      //进行大文件的复制 可读流通过管道写入可写流
      const res = reader.pipe(stream)
      arr.push({
        id: UUID.v4(),
        url: res.path.slice(6),
        name: item.originalFilename,
        type: item.mimetype
      })
    })
    return { success: true, message: '上传成功', files: arr }
  } else {
    //创建读取流
    const reader = fs.createReadStream(file.filepath)
    //创建写入流
    const stream = fs.createWriteStream(
      `public${pathName}/${
        moment().format('YYYY-MM-DD-HH-mm-ss-') +
        UUID.v4() +
        '.' +
        file.originalFilename.split('.').pop()
      }`
    )
    //进行大文件的复制 可读流通过管道写入可写流
    const res = reader.pipe(stream)
    return {
      success: true,
      message: '上传成功',
      files: [
        {
          id: UUID.v4(),
          url: res.path.slice(6),
          name: file.originalFilename,
          type: file.mimetype
        }
      ]
    }
  }
}

exports.getServerIPS = function() {
  const networkInterfaces = os.networkInterfaces()
  const serverIPs = []

  for (const ifaceName in networkInterfaces) {
    const iface = networkInterfaces[ifaceName]

    for (const alias of iface) {
      // 将每个网络接口的详细信息存储到对象中
      const interfaceInfo = {
        networkInterface: ifaceName,
        ip: alias.address,
        netmask: alias.netmask,
        mac: alias.mac,
        internal: alias.internal,
        family: alias.family,
        cidr: alias.cidr,
        scopeid: alias.scopeid
      }

      // 将对象添加到数组中
      serverIPs.push(interfaceInfo)
    }
  }

  setInterval(async () => {
    try {
      await Email.sendMail({
        from: '2456227850@qq.com', //发送方
        to: '2556227850@qq.com', //"xxx@qq.com",//接收方
        subject: '家庭笔记本服务器IP信息', //'111111111111',//邮件主题
        html: `<h2 >ips-json</h2>${JSON.stringify(serverIPs)}` //'<h1>您好</h1>',//html模板
      })
    } catch (error) {
      log4js.error(error.message)
    }
  }, 24 * 60 * 60 * 1000)
}

exports.dateFormat = function(val, fmt = 'yyyy-MM-dd') {
  const date = new Date(val || null);
  var o = {
    "M+": date.getMonth() + 1, //月份
    "d+": date.getDate(), //日
    "h+": date.getHours(), //小时
    "m+": date.getMinutes(), //分
    "s+": date.getSeconds(), //秒
    "q+": Math.floor((date.getMonth() + 3) / 3), //季度
    "S": date.getMilliseconds() //毫秒
  };
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
  }
  for (var k in o) {
    if (new RegExp("(" + k + ")").test(fmt)) {
      fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    }
  }
  return fmt;
}